package hn.sigit.view;

import hn.sigit.dao.hnd.administrative.HND_LegalPersonDAO;
import hn.sigit.model.hnd.administrative.HND_LegalPerson;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;


@Name("legalPersonHelper")
@Scope(value = ScopeType.CONVERSATION)
@AutoCreate
public class LegalPersonHelper extends MantHelper<HND_LegalPerson> {
	private static final long serialVersionUID = 1L;

	protected final String BY_RTN = "0";
	protected final String BY_NAME = "1";

	
	@Override
	public List<HND_LegalPerson> getPersonList() {
		if (personList == null) {
			personList = new ArrayList<HND_LegalPerson>();
		}
		return personList;
	}
	@Override
	public void setPersonList(List<HND_LegalPerson> personList) {
		this.personList = personList;
	}

	@Override
	public String addNew() {
		setSelected(new HND_LegalPerson());
		editing = true;
		adding = true;
		
		return null;
	}

	@Override
	public String edit(HND_LegalPerson lp) {
		setSelected(lp);
		editing = true;
		adding = false;
		
		return null;
	}

	@Override
	public String view(HND_LegalPerson lp) {
		setSelected(lp);
		editing = false;
		adding = false;
		
		return null;
	}

	@Override
	public String delete(HND_LegalPerson lp) {
		HND_LegalPersonDAO.delete(lp);
		personList.remove(lp);
		
		return null;
	}

	@Override
	public String select(HND_LegalPerson lp) {
		setSelected(lp);
		super.doSelection();
		return null;
	}

	@Override
	public String saveSelected() {
		HND_LegalPersonDAO.save(getSelected());
		if (adding) {
			getPersonList().clear();
			getPersonList().add(getSelected());
		}
		
		return null;
	}

	@Override
	public String quickSearch() {
		searchText = searchText.trim();
		List<HND_LegalPerson> searchResultList = new ArrayList<HND_LegalPerson>();
		
		if (searchSelector.equals(BY_RTN)) {
			searchText = searchText.replaceAll("-", "");
			searchResultList = wrapSingle(HND_LegalPersonDAO.loadLegalPersonByRTN(searchText));
		}
		else if (searchSelector.equals(BY_NAME)) {
			searchResultList = HND_LegalPersonDAO.loadLegalPersonsByName(searchText);
		}
		
		if (searchResultList.size() == 0) {
			FacesContext.getCurrentInstance().addMessage("",
					new FacesMessage(
							FacesMessage.SEVERITY_INFO,
							resBundle.loadMessage("txt.no_search_results"),
							""
					)
			);
		}

		setPersonList(searchResultList);
		
		return null;
	}

	
	
	public String getBY_RTN() {
		return BY_RTN;
	}

	public String getBY_NAME() {
		return BY_NAME;
	}
}
